/**
 ******************************************************************************
 * @file           : bsp_24cxx.c
 * @brief          : 24CXX EEPROM Driver (STM32F4xx)
 ******************************************************************************
 */

#include "./Devices/24CXX/bsp_24cxx_config.h"
#include "./Devices/24CXX/bsp_24cxx.h"
#include "./BSP/IIC/bsp_iic.h"

uint8_t eeprom_init(void)
{
    if (eeprom_check() == 0)
    {
        log_i("24CXX EEPROM found");
        return 0;
    }
    
    log_e("24CXX EEPROM not found");
    return 1;
}

void eeprom_deinit(void)
{
    /* 无需特殊处理 */
}

uint8_t eeprom_read(uint16_t addr, uint8_t *buf, uint16_t len)
{
    if (buf == NULL || len == 0)
    {
        return 1;
    }
    
    return iic_read_bytes(EEPROM_I2C_ADDR, addr, buf, len);
}

uint8_t eeprom_write(uint16_t addr, const uint8_t *buf, uint16_t len)
{
    if (buf == NULL || len == 0)
    {
        return 1;
    }
    
    uint16_t written = 0;
    
    while (written < len)
    {
        uint16_t page_offset = addr % EEPROM_PAGE_SIZE;
        uint16_t bytes_to_write = EEPROM_PAGE_SIZE - page_offset;
        
        if (bytes_to_write > (len - written))
        {
            bytes_to_write = len - written;
        }
        
        if (iic_write_bytes(EEPROM_I2C_ADDR, addr, (uint8_t *)&buf[written], bytes_to_write) != 0)
        {
            return 1;
        }
        
        HAL_Delay(5);
        
        written += bytes_to_write;
        addr += bytes_to_write;
    }
    
    return 0;
}

uint8_t eeprom_check(void)
{
    return iic_check_device(EEPROM_I2C_ADDR);
}
